package com.food.restaurantpro.imageloader;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.food.restaurantpro.R;
import com.food.restaurantpro.RestaurantApp;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class FileCache {

	private File cacheDir;

	public FileCache(Context context) {
		// Find the dir to save cached images
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED))
			cacheDir = new File(
					android.os.Environment.getExternalStorageDirectory(),
					"LazyListRestaurant");
		else
			cacheDir = context.getCacheDir();
		if (!cacheDir.exists())
			cacheDir.mkdirs();
	}

	public File getFile(String url) {
		// I identify images by hashcode. Not a perfect solution, good for the
		// demo.
		String filename = String.valueOf(url.hashCode()) + url.substring(url.lastIndexOf('/') + 1);
		// Another possible solution (thanks to grantland)
		// String filename = URLEncoder.encode(url);
		File f = new File(cacheDir, filename);
		return f;

	}

	public void clear() {
		File[] files = cacheDir.listFiles();
		if (files == null)
			return;
		for (File f : files)
			f.delete();
	}

	//get bitmap from cache
	public Bitmap getBitmapByUrl(String url) {
		if(url != null) {
			File f = getFile(url);
			if (f.exists()) {
				try {
					FileInputStream stream = new FileInputStream(f);
					BitmapFactory.Options options = new BitmapFactory.Options();
//					options.inSampleSize = 4;
					Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, options);//decodeStream(stream, null, options);
					stream.close();
					if(bitmap != null) {
						return bitmap;
					}
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		}
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 4;
		Bitmap bitmap = BitmapFactory.decodeResource(RestaurantApp.CURRENT_CONTEXT.getResources(), R.drawable.image0, options);
		return bitmap;
	}
}